<!--
 * @Description: 创建任务
 * @Author: lixianggang
 * @Date: 2022-11-10 13:38:51
 * @LastEditors: lixianggang
 * @LastEditTime: 2023-01-17 16:51:04
-->
<template>
  <div class="page-wrap" v-loading="pageLoading">
    <div class="header-btn">
      <div>{{this.$route.query.type == '2' ? '编辑任务' : '创建任务'}}</div>
      <div>
        <el-button type="primary" @click="confirm">确认</el-button>
        <el-button type="info" plain @click="goBack">返回</el-button>
      </div>
    </div>
    <el-form ref="createForm" :model="createForm" :rules="rules" label-width="160px" label-position="right">
      <div class="wrap g-card">
        <div class="title-header">选择客户旅程</div>
        <div class="base-set ml20">
          <el-form-item label="客户旅程">{{ flowName }}</el-form-item>
          <el-form-item label="指定客户旅程阶段">{{ flowNodeName }}</el-form-item>
          <el-form-item label="在以下客户旅程不执行" prop="unexecuteFlowIdList">
            <el-select v-model="createForm.unexecuteFlowIdList" placeholder="请选择" multiple style="width: 80%;">
              <el-option v-for="item in flowNameList" :key="item.flowId" :value="item.flowId" :label="item.flowName" />
            </el-select>
          </el-form-item>
        </div>
      </div>
      <div class="wrap g-card">
        <div class="title-header">内容</div>
        <el-form-item label="请设置发送时间" required class="multiple-form">
          <el-form-item prop="sendDay">
            <el-input placeholder="选择天数" v-model="createForm.sendDay" type="number" min="0"></el-input>
          </el-form-item>
          <div>天后</div>
          <el-form-item prop="sendTime">
            <el-time-picker placeholder="选择时间" v-model="createForm.sendTime" style="width: 100%;" format="HH:mm" value-format="HH:mm"></el-time-picker>
          </el-form-item>
          <div>发送</div>
        </el-form-item>
        <el-form-item label="请选择触达形式" prop="sendType">
          <el-radio-group v-model="createForm.sendType">
            <el-radio v-for="item in sendTypeList" :key="item.dictValue" :label="item.dictValue">
              {{ item.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="文本内容" prop="content">
          <el-input v-model="createForm.content" clearable maxlength="200" type="textarea" show-word-limit rows="4" style="width: 60%;"></el-input>
        </el-form-item>
        <el-form-item label="发送内容" prop="auditRemark">
          <NormalSelectMaterial v-if="operateFlag" :selectedList="createForm.mediaContentDetails" @confirmSelect="confirmSelectFn" />
        </el-form-item>
        <el-form-item label="二维码" prop="qrState">
          <NormalQrCode v-if="operateFlag" :disabled="operateFlag == 'DETAIL'" :codeInfo="codeParams" @selectedSure="qrCodeConfrim" @deleteSeletedQrcode="deleteSeletedQrcode" />
        </el-form-item>
      </div>
    </el-form>
    <dialog-text text="该时间线线索已存在，是否更新？" :visible.sync="visible" @confirm="handleUpdateJourney">
    </dialog-text>
  </div>
</template>

<script>
import { addJourneyTask, addJourneyTaskCheck, getFlowNameList, queryJourneyTask, updateJourneyTask } from '@/api/operate/automarket'
import DialogText from '@/components/DialogText.vue'

export default {
  components: { DialogText },
  data() {
    return {
      flowName: '',
      flowNodeName: '',
      createForm: {
        flowId: this.$route.query.flowId,
        unexecuteFlowIdList: '',
        sendDay: '',
        sendTime: '',
        sendType: '',
        content: '',
        qrState: '1',
        qrType: '',
        activityName: '',
        codeUrl: '',
        mediaContentDetails: []
      },
      rules: {
        sendDay: [{ required: true, message: '请选择发送时间', trigger: 'blue' }],
        sendTime: [{ required: true, message: '请选择发送时间', trigger: 'change' }],
        sendType: [{ required: true, message: '请选择触达形式', trigger: 'change' }],
        content: [{ required: true, message: '请填写文本内容', trigger: 'blur' }]
      },
      flowNameList: [],
      sendTypeList: [],
      // 1通用线索 0专用线索
      type: this.$route.query.type,
      flowNodeId: this.$route.query.flowNodeId,
      pageLoading: false,
      visible: false,
      currentParam: {},
      operateFlag: '',
      codeParams: {
        qrState: '1',
        qrType: '',
        activityName: '',
        codeUrl: '',
        qrId: ''
      },
    }
  },
  methods: {
    // 删除二维码
    deleteSeletedQrcode() {
      this.codeParams.qrType = '';
      this.codeParams.activityName = '';
      this.codeParams.codeUrl = '';
      this.codeParams.qrId = '';
    },
    qrCodeConfrim(data) {
      if (data) {
        this.codeParams = {
          qrState: data.qrState,
          qrType: data.qrType,
          activityName: data.activityName,
          codeUrl: data.qrCode || data.codeUrl,
          qrId: data.qrId
        }
      } else {
        this.codeParams = {
          qrState: 1,
          qrType: '',
          activityName: '',
          codeUrl: '',
          qrId: ''
        }
      }
    },
    goBack() {
      this.$router.back()
    },
    async confirm() {
      if (this.createForm.mediaContentDetails) {
        this.createForm.mediaContentDetails.forEach(item => {
          if (item.mediaType == '3') {
            item.materialUrl = window.globalConfig.SHARE_URL + '/linkFile?id=' + item.id
          } else if (item.mediaType == '4') {
            item.materialUrl = window.globalConfig.SHARE_URL + '/linkArticle?id=' + item.id
          } else if (item.mediaType == '10') {
            item.materialUrl = window.globalConfig.SHARE_URL + '/linkForm?id=' + item.id
          }
        })
      }
      const param = {
        ...this.createForm,
        ...this.codeParams,
        // 专用和编辑线索传flowNodeIdList
        flowNodeIdList: this.type === '0' || this.type === '2' ? [this.flowNodeId] : [],
        allFlag: this.type === '1' ? 'Y' : '',
        unexecuteFlowIdList: this.createForm.unexecuteFlowIdList.toString()
      }
      this.currentParam = param
      if (param.mediaContentDetails.length > 9) {
        this.$message.error("所有素材不能超过九个！")
        return
      }
      if (param.qrState == '0' && !param.codeUrl) {
        this.$message.error('请选择二维码！');
        return
      }

      try {
        this.pageLoading = true
        let resCheck = await addJourneyTaskCheck(param)
        if (resCheck.data === true) {
          this.handleAddJourney()
        } else {
          this.visible = true
        }
        this.pageLoading = false
      } catch (error) {
        this.pageLoading = false
      }
    },
    async handleAddJourney() {
      let resTask = await addJourneyTask(this.currentParam)
      if (resTask.code === 200) {
        this.$message.success('操作成功')
        this.goBack()
      }
    },
    async handleUpdateJourney() {
      let resTask = await updateJourneyTask(this.currentParam)
      if (resTask.code === 200) {
        this.$message.success('操作成功')
        this.goBack()
      }
    },
    async init() {
      this.pageLoading = true
      try {
        let res = await getFlowNameList()
        res.code === 200 && (this.flowNameList = res.data.filter(item => item.flowId !== this.createForm.flowId))
        this.flowName = res.data.filter(item => item.flowId === this.createForm.flowId)?.[0].flowName
        this.flowNodeName = this.type === '1' ? '全阶段' : this.$route.query.flowNodeName
        // 编辑返显
        if (this.type === '2') {
          let res = await queryJourneyTask(this.$route.query.id)
          if (res.code === 200) {
            this.createForm = {
              ...this.createForm,
              ...res.data,
              sendType: res.data.sendType + '',
              unexecuteFlowIdList: res.data.unexecuteFlowIdList && res.data.unexecuteFlowIdList?.split(','),
              mediaContentDetails: res.data.mediaContentDetails || []
            }
            this.codeParams = {
              activityName: res.data.activityName || '',
              codeUrl: res.data.codeUrl || '',
              qrState: String(res.data.qrState) || '',
              qrType: res.data.qrType || '',
              qrId: '',
            }
            this.operateFlag = 'EDIT'
          }
        } else {
          this.operateFlag = 'ADD'
        }
        this.pageLoading = false
      } catch (error) {
        this.pageLoading = false
      }
    },
    // 确定选择的素材
    confirmSelectFn(val) {
      this.createForm.mediaContentDetails = val;
    },
  },
  mounted() {
    this.getDicts('send_type').then((res) => {
      if (res.code === 200) {
        this.sendTypeList = res.data
      }
    })
    this.init()
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/base.scss";

.page-wrap {
  .header-btn {
    @include headerBtn;
    margin-bottom: 16px;
  }

  .wrap {
    @include titleWrap;
  }

  .multiple-form {
    ::v-deep .el-form-item__content {
      display: flex;
      align-items: center;

      .el-form-item {
        padding: 0 10px;
      }

      .el-form-item:first-of-type {
        padding-left: 0px;
      }
      .el-input__inner {
        padding-right: 0;
      }
    }
  }
}
</style>
